import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import {
  Table, Button, Modal, Form, Input, DatePicker, Upload, message,
  Select, Space, Row, Col, Tooltip, Tag, Popconfirm, Divider, Image
} from 'antd';
import {
  UploadOutlined,
  SearchOutlined,
  DownloadOutlined,
  PlusOutlined,
  FileExcelOutlined,
  DeleteOutlined,
  LoadingOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';
import Uploads from "$components/Uploads";
import moment from 'moment';
import { 
  getColumns, 
  trademarkStatusOptions,
  internationalClassOptions
} from './trademarkColumns';
import {
  getTrademarkList,
  getTrademarkDetail,
  addTrademark,
  updateTrademark,
  deleteTrademark,
  batchDeleteTrademark,
  importTrademark,
  exportTrademark
} from '../actions/trademark';
import '../styles.css';

const { RangePicker } = DatePicker;

function TrademarkManagement(props) {
  const {
    dispatch,
    addTrademarkResult,
    updateTrademarkResult,
    deleteTrademarkResult,
    batchDeleteTrademarkResult,
    importTrademarkResult
  } = props;
  
  // 状态定义
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchForm] = Form.useForm();
  const [editForm] = Form.useForm();
  const [editingRecord, setEditingRecord] = useState(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [importModalVisible, setImportModalVisible] = useState(false);
  const [uploadFile, setUploadFile] = useState(null);
  const [trademarkList, setTrademarkList] = useState([]);
  const [searchParams, setSearchParams] = useState({});
  const [trademarkImage, setTrademarkImage] = useState([]);
  const [uploading, setUploading] = useState(false);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  
  // 获取商标列表
  const fetchTrademarkList = (params = {}) => {
    setLoading(true);
    const queryParams = {
      page: params.current || pagination.current,
      pageSize: params.pageSize || pagination.pageSize,
      keyword: params.keyword || searchParams.keyword || "",
      trademark_status: params.trademark_status || searchParams.trademark_status || "",
      application_date_start: params.application_date_start || searchParams.application_date_start || "",
      application_date_end: params.application_date_end || searchParams.application_date_end || "",
      ...params,
    };
    
    dispatch(getTrademarkList(queryParams))
      .then(res => {
        if (res && res.payload) {
          console.log(res.payload);
          setTrademarkList(res.payload.data.data.list);
          setPagination({
            ...pagination,
            current: res.payload.data.data.page || pagination.current,
            pageSize: res.payload.data.data.pageSize || pagination.pageSize,
            total: res.payload.data.data.total || 0,
          });
        }
        setLoading(false);
      })
      .catch(() => {
        setLoading(false);
      });
  };

  // 初始加载
  useEffect(() => {
    fetchTrademarkList();
  }, []);

  // 处理列表数据更新
  useEffect(() => {
    if (trademarkList) {
      setLoading(false);
    }
  }, [trademarkList]);

  // 处理新增/编辑结果
  useEffect(() => {
    if (addTrademarkResult) {
      if (addTrademarkResult.error) {
        message.error(addTrademarkResult.error || "添加商标失败");
      } else {
        message.success("添加商标成功");
        setModalVisible(false);
        fetchTrademarkList();
      }
    }
  }, [addTrademarkResult]);

  useEffect(() => {
    if (updateTrademarkResult) {
      if (updateTrademarkResult.error) {
        message.error(updateTrademarkResult.error || "更新商标失败");
      } else {
        setModalVisible(false);
        fetchTrademarkList();
      }
    }
  }, [updateTrademarkResult]);

  // 处理删除结果
  useEffect(() => {
    if (deleteTrademarkResult) {
      if (deleteTrademarkResult.error) {
        message.error(deleteTrademarkResult.error || "删除商标失败");
      } else {
        message.success("删除商标成功");
        fetchTrademarkList();
      }
    }
  }, [deleteTrademarkResult]);

  // 处理批量删除结果
  useEffect(() => {
    if (batchDeleteTrademarkResult) {
      if (batchDeleteTrademarkResult.error) {
        message.error(batchDeleteTrademarkResult.error || "批量删除商标失败");
      } else {
        message.success("批量删除商标成功");
        setSelectedRowKeys([]);
        fetchTrademarkList();
      }
    }
  }, [batchDeleteTrademarkResult]);

  // 处理导入结果
  useEffect(() => {
    if (importTrademarkResult) {
      if (importTrademarkResult.error) {
        message.error(importTrademarkResult.error || "导入商标失败");
      } else {
        message.success("导入商标成功");
        setImportModalVisible(false);
        setUploadFile(null);
        fetchTrademarkList();
      }
    }
  }, [importTrademarkResult]);

  // 表格变化处理
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination({
      ...pagination,
      current: pagination.current,
      pageSize: pagination.pageSize,
    });

    fetchTrademarkList({
      current: pagination.current,
      pageSize: pagination.pageSize,
      sortField: sorter.field,
      sortOrder: sorter.order,
      ...filters,
    });
  };

  // 搜索处理
  const handleSearch = (values) => {
    const params = {
      current: 1,
      keyword: values.keyword,
      trademark_status: values.trademark_status,
    };
    
    if (values.application_date && values.application_date.length === 2) {
      params.application_date_start = values.application_date[0].format('YYYY-MM-DD');
      params.application_date_end = values.application_date[1].format('YYYY-MM-DD');
    }
    
    setSearchParams(params);
    fetchTrademarkList(params);
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    setSearchParams({});
    fetchTrademarkList({ current: 1 });
  };

  // 处理商标图片数据
  const processTrademarkImage = (record) => {
    if (record && record.trademark) {
      try {
        // 如果是JSON字符串，解析它
        const trademarkData = typeof record.trademark === 'string' 
          ? JSON.parse(record.trademark) 
          : record.trademark;
        
        // 如果是数组，直接使用
        if (Array.isArray(trademarkData)) {
          return trademarkData;
        }
        // 如果是单个对象，转换为数组
        else if (trademarkData && (trademarkData.url || trademarkData.storageUrl)) {
          return [trademarkData];
        }
      } catch (e) {
        console.error("解析商标图片数据失败", e);
      }
    }
    return [];
  };

  // 编辑商标
  const onEdit = (record) => {
    setEditingRecord(record);
    const trademarkImages = processTrademarkImage(record);
    
    editForm.setFieldsValue({
      ...record,
      application_date: record.application_date ? dayjs(record.application_date) : null,
      registration_announcement_date: record.registration_announcement_date ? dayjs(record.registration_announcement_date) : null,
      expiration_date: record.expiration_date ? dayjs(record.expiration_date) : null,
    });
    
    setTrademarkImage(trademarkImages);
    setModalVisible(true);
  };

  // 新增商标
  const onAdd = () => {
    setEditingRecord(null);
    editForm.resetFields();
    editForm.setFieldsValue({
      trademark_status: '申请中'
    });
    setTrademarkImage([]);
    setModalVisible(true);
  };

  // 删除商标
  const onDelete = (record) => {
    Modal.confirm({
      title: "确认删除？",
      content: `确定要删除商标「${record.trademark_name}」吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: () => {
        dispatch(deleteTrademark(record.id));
      },
    });
  };

  // 批量删除商标
  const onBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning("请至少选择一条记录");
      return;
    }
    
    Modal.confirm({
      title: "确认删除",
      content: `确定要删除选中的 ${selectedRowKeys.length} 条商标记录吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: () => {
        dispatch(batchDeleteTrademark(selectedRowKeys));
      },
    });
  };

  // 处理上传状态变化
  const handleUploadStateChange = (state) => {
    setUploading(state.uploading);
  };

  // 处理上传图片变化
  const handleTrademarkChange = (files) => {
    setTrademarkImage(files);
  };

  // 提交表单处理
  const handleEditOk = () => {
    editForm
      .validateFields()
      .then((values) => {
        // 转换日期格式
        const formattedValues = {
          ...values,
          application_date: values.application_date ? values.application_date.format('YYYY-MM-DD') : null,
          registration_announcement_date: values.registration_announcement_date ? values.registration_announcement_date.format('YYYY-MM-DD') : null,
          expiration_date: values.expiration_date ? values.expiration_date.format('YYYY-MM-DD') : null,
          trademark: trademarkImage // 使用商标图片数据
        };

        if (editingRecord) {
          // 更新商标
          dispatch(updateTrademark(editingRecord.id, formattedValues));
        } else {
          // 添加商标
          dispatch(addTrademark(formattedValues));
        }
      })
      .catch((info) => {
        console.log('校验失败:', info);
        message.error('表单验证失败，请检查必填字段');
      });
  };

  // 将File对象转换为base64
  const getBase64 = (file, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(file);
  };

  // 预览图片
  const handlePreview = (file) => {
    if (file.url || file.preview) {
      setPreviewImage(file.url || file.preview);
      setPreviewVisible(true);
    } else if (file.originFileObj) {
      getBase64(file.originFileObj, url => {
        setPreviewImage(url);
        setPreviewVisible(true);
      });
    }
  };

  // 导入商标
  const handleImport = () => {
    if (!uploadFile) {
      message.warning("请选择要导入的文件");
      return;
    }
    
    const formData = new FormData();
    formData.append('file', uploadFile);
    
    dispatch(importTrademark(formData));
  };

  // 导出商标
  const handleExport = () => {
    // 构建查询参数
    const params = {
      ...searchParams
    };
    
    // 如果有选中行，则只导出选中行
    if (selectedRowKeys.length > 0) {
      params.ids = selectedRowKeys.join(',');
    }

    // 直接下载文件
    const exportUrl = `${window.location.origin}/_api/brandManagement/export?${new URLSearchParams(params).toString()}`;
    
    // 创建一个临时链接并点击，触发下载
    const link = document.createElement("a");
    link.href = exportUrl;
    link.target = "_blank";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedKeys) => {
      setSelectedRowKeys(selectedKeys);
    }
  };

  // 自定义表格列，处理商标图片显示
  const customColumns = (baseColumns) => {
    // 找到商标列的索引
    const trademarkColumnIndex = baseColumns.findIndex(col => col.dataIndex === 'trademark');
    
    if (trademarkColumnIndex !== -1) {
      // 修改商标列的渲染方式
      baseColumns[trademarkColumnIndex].render = (text, record) => {
        if (text && typeof text === 'object') {
          // 如果是数组，取第一个图片
          const imageData = Array.isArray(text) ? text[0] : text;
          
          if (imageData && (imageData.url || imageData.storageUrl)) {
            const imageUrl = imageData.url || `/_file-server/${imageData.storageUrl}`;
            return (
              <Image
                src={imageUrl}
                alt="商标图片"
                style={{ width: 50, height: 50, objectFit: 'contain' }}
                preview={{
                  mask: <div>预览</div>,
                }}
              />
            );
          }
        }
        return <span>无图片</span>;
      };
      
      // 修改列标题
      baseColumns[trademarkColumnIndex].title = '商标图片';
    }
    
    return baseColumns;
  };

  return (
    <div>
      <div className="page-header" style={{ marginBottom: 16 }}>
        <h2>商标管理</h2>
      </div>
      
      {/* 搜索表单 */}
      <div 
        className="search-area" 
        style={{
          marginBottom: 16,
          padding: "16px",
          backgroundColor: "#f0f2f5",
          borderRadius: "4px",
        }}
      >
        <Form 
          form={searchForm} 
          layout="inline" 
          onFinish={handleSearch}
        >
          <Form.Item name="keyword" label="关键词:">
            <Input placeholder="商标名称/注册号" allowClear style={{ width: 240 }} />
          </Form.Item>
          
          <Form.Item name="trademark_status" label="商标状态:">
            <Select
              placeholder="请选择商标状态"
              allowClear
              style={{ width: 150 }}
            >
              {trademarkStatusOptions.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item name="application_date" label="申请日期:">
            <RangePicker allowClear style={{ width: 240 }} />
          </Form.Item>
          
          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              icon={<SearchOutlined />}
            >
              查询
            </Button>
          </Form.Item>
          
          <Form.Item>
            <Button onClick={handleReset}>
              重置
            </Button>
          </Form.Item>
          
          <Form.Item>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={onAdd}
              style={{ marginRight: 8 }}
            >
              新增商标
            </Button>
          </Form.Item>
          
          <Form.Item>
            <Button
              type="primary"
              icon={<UploadOutlined />}
              onClick={() => setImportModalVisible(true)}
              style={{ marginRight: 8 }}
            >
              导入商标
            </Button>
          </Form.Item>
          
          <Form.Item>
            <Button
              type="primary"
              icon={<DownloadOutlined />}
              onClick={handleExport}
              style={{ marginRight: 8 }}
            >
              导出商标
            </Button>
          </Form.Item>
          
          {selectedRowKeys.length > 0 && (
            <Form.Item>
              <Button
                type="danger"
                icon={<DeleteOutlined />}
                onClick={onBatchDelete}
              >
                批量删除({selectedRowKeys.length})
              </Button>
            </Form.Item>
          )}
        </Form>
      </div>
      
      {/* 数据表格 */}
      <div className="trademark-table-container">
      <Table
          rowKey="id"
          rowSelection={rowSelection}
          columns={customColumns(getColumns(onEdit, onDelete))}
          dataSource={trademarkList || []}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ["10", "20", "50", "100"],
          }}
          loading={loading}
          onChange={handleTableChange}
          scroll={{ x: "max-content", y: 500 }}
          size="small"
          rowClassName={() => "custom-table-row"}
        />
      </div>
      
      {/* 编辑/添加商标弹窗 */}
      <Modal
        title={editingRecord ? "编辑商标信息" : "添加商标信息"}
        open={modalVisible}
        onOk={handleEditOk}
        onCancel={() => setModalVisible(false)}
        confirmLoading={loading || uploading}
        width={800}
        bodyStyle={{ maxHeight: "600px", overflow: "auto" }}
        okText="保存"
        cancelText="取消"
        maskClosable={false}
      >
        <Form
          form={editForm}
          layout="horizontal"
          labelCol={{ flex: "160px" }}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="trademark_name"
                label="商标名称"
                rules={[{ required: true, message: '请输入商标名称' }]}
              >
                <Input placeholder="请输入商标名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="registration_number"
                label="注册号"
                rules={[{ required: true, message: '请输入注册号' }]}
              >
                <Input placeholder="请输入注册号" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            label="商标图片"
            rules={[{ required: true, message: '请上传商标图片' }]}
          >
            <Uploads
              listType="picture-card"
              uploadType="project"
              maxFilesNum={1}
              maxFileSize={2}
              isQiniu={true}
              fileTypes={["png", "jpg", "jpeg"]}
              onStateChange={handleUploadStateChange}
              onChange={handleTrademarkChange}
              value={trademarkImage}
              defaultValue={trademarkImage}
            />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="international_class"
                label="国际分类"
              >
                <Select placeholder="请选择国际分类" allowClear>
                  {internationalClassOptions.map(option => (
                    <Select.Option key={option.value} value={option.value}>
                      {option.label}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="trademark_status"
                label="商标状态"
                rules={[{ required: true, message: '请选择商标状态' }]}
              >
                <Select placeholder="请选择商标状态">
                  {trademarkStatusOptions.map(option => (
                    <Select.Option key={option.value} value={option.value}>
                      {option.label}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="application_date"
                label="申请日期"
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="registration_announcement_date"
                label="注册公告日期"
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="expiration_date"
                label="到期日期"
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea rows={3} placeholder="请输入描述" />
          </Form.Item>
        </Form>
      </Modal>
      
      {/* 图片预览弹窗 */}
      <Modal
        open={previewVisible}
        title="商标图片预览"
        footer={null}
        onCancel={() => setPreviewVisible(false)}
      >
        <img alt="商标图片预览" style={{ width: '100%' }} src={previewImage} />
      </Modal>
      
      {/* 导入商标弹窗 */}
      <Modal
        title="导入商标数据"
        open={importModalVisible}
        onOk={handleImport}
        onCancel={() => {
          setImportModalVisible(false);
          setUploadFile(null);
        }}
        okText="导入"
        cancelText="取消"
      >
        <Upload
          beforeUpload={(file) => {
            // 只接受Excel文件
            const isExcel =
              file.type ===
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
              file.type === "application/vnd.ms-excel";
            if (!isExcel) {
              message.error("只能上传Excel文件!");
              return Upload.LIST_IGNORE;
            }
            setUploadFile(file);
            return false; // 阻止自动上传
          }}
          fileList={uploadFile ? [uploadFile] : []}
          onRemove={() => setUploadFile(null)}
          maxCount={1}
        >
          <Button icon={<UploadOutlined />}>选择Excel文件</Button>
        </Upload>
        <div style={{ marginTop: 16 }}>
          <p>注意：导入前请确保数据格式正确，商标名称和注册号为必填项</p>
          <p>请按照模板格式准备导入数据</p>
        </div>
      </Modal>
    </div>
  );
}

function mapStateToProps(state) {
  const {
    trademarkList,
    addTrademarkResult,
    updateTrademarkResult,
    deleteTrademarkResult,
    batchDeleteTrademarkResult,
    importTrademarkResult
  } = state.trademark || {};
  
  return {
    trademarkList,
    addTrademarkResult,
    updateTrademarkResult,
    deleteTrademarkResult,
    batchDeleteTrademarkResult,
    importTrademarkResult
  };
}

export default connect(mapStateToProps)(TrademarkManagement);
